package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServicelmpl implements DishService
{
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetMealDishMapper setMealDishMapper;
    @Transactional//保证原子性（要不全成功，要不全失败）
    public void saveWithFlavor(DishDTO dishDTO)
    {
        Dish dish=new Dish();
        //往菜品表插入1条数据
            //拷贝属性
            BeanUtils.copyProperties(dishDTO,dish);
            //设置起售状态
            dish.setStatus(StatusConstant.ENABLE);
            dishMapper.insert(dish);
            //获取insert语句生成的主键值
            long dishId=dish.getId();
        //往口味表插入N条数据
        List<DishFlavor> flavors=dishDTO.getFlavors();
        if( !flavors.equals(null) && flavors.size()>0)
        {
            //圆括号里的fishFlavor是随便起的名字，给遍历出来的对象起的
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO)
    {
        //开始分页查询（页码，每页条数）
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        //用Page对象接受
        Page<Dish> page=dishMapper.pageQuery(dishPageQueryDTO);
        long total=page.getTotal();
        List<Dish> records=page.getResult();
        return new PageResult(total,records);
    }

    /**
     * 菜品起售、停售
     * @param status
     * @param id
     */
    @Override
    public void startOrstop(Integer status, long id)
    {
        Dish dish=new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.update(dish);
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
     public DishVO getByIdWithFlavor(long id)
     {
         //根据菜品id查询基本信息
         Dish dish=dishMapper.getById(id);
         //根据菜品id查询口味信息
         List<DishFlavor> dishFlavors=dishFlavorMapper.getByDishId(id);
         //把上面查出来的两部分数据封装到VO中
         DishVO dishVO=new DishVO();
         BeanUtils.copyProperties(dish,dishVO);
         dishVO.setFlavors(dishFlavors);
         return dishVO;
     }

    /**
     * 根据分类Id查询菜品信息
     * @param categoryId
     * @return
     */
    public List<Dish> getByCategoryId(long categoryId)
    {
        List<Dish> dishes=dishMapper.getByCateforyId(categoryId);
        return dishes;
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    public void deleteBatch(List<Long> ids)
    {

        for (Long id : ids)
        {
            Dish dish=dishMapper.getById(id);
            //判断当前菜品是否能够删除（是否存在起售中）
            if(dish.getStatus().equals(StatusConstant.ENABLE))
            {
                //说明处于起售状态
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断当前菜品是否能够删除（是否被关联）
        List<Long> setMealIds = setMealDishMapper.getSetMealIdByDishIds(ids);
        if(setMealIds!=null && setMealIds.size()>0)
        {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中的菜品（效率低的版本，每次执行2条sql语句）
//        for (Long id: ids)
//        {
//            删除对应的口味表中的数据
//            dishMapper.deleteById(id);
//
//            dishFlavorMapper.deleteDishById(id);
//        }
        //删除菜品表中的菜品（效率高的版本，只执行1条sql语句）
            dishMapper.deleteByIds(ids);
            dishFlavorMapper.deleteDishByIds(ids);
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Override
    public void updateWithFlavor(DishDTO dishDTO)
    {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改基本信息
        dishMapper.update(dish);
        //修改口味信息（先删除旧的，再新增）
        dishFlavorMapper.deleteDishById(dishDTO.getId());
        List<DishFlavor> flavors=dishDTO.getFlavors();
        if( !flavors.equals(null) && flavors.size()>0)
        {
            //圆括号里的fishFlavor是随便起的名字，给遍历出来的对象起的
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish)
    {
        List<Dish> dishList = dishMapper.getByCateforyId(dish.getCategoryId());

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList)
        {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
